package com.atguigu.flink.state;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * Created by Smexy on 2023/4/10
 *
 *   keyed state，都是在当前Task初始化时，从备份中获取状态。
 *
 *   每种key各自操作各自的ListState
 *
 *
 * 针对每种传感器输出最高的3个水位值
 */
public class Demo5_KeyedListState
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop102", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .process(new KeyedProcessFunction<String, WaterSensor, String>()
                   {
                       //用来存储当前前三水位的 集合
                       private ListState<Integer> top3;

                       // keyed state，都是在当前Task初始化时，从备份中获取状态。
                       @Override
                       public void open(Configuration parameters) throws Exception {
                           top3 = getRuntimeContext().getListState(new ListStateDescriptor<>("top3", Integer.class));
                       }

                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                          //把当前元素添加到集合中
                           top3.add(value.getVc());
                           //在集合中进行排序和对比，取前3
                           List<Integer> top3Vc = StreamSupport.stream(this.top3.get().spliterator(), true)
                                                                .sorted(Comparator.reverseOrder())
                                                                .limit(3)
                                                                .collect(Collectors.toList());

                           //只存前三名
                           top3.update(top3Vc);

                           out.collect(ctx.getCurrentKey() + "的前3:" +top3Vc.toString());

                       }
                   })
                   .print();

                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
